/**
 * @file 配置文件
 * @author yanlingling@baidu.com
 */
//banner图片
var BANNER_INFO_PATH = 'index/banners/get.ajax';
//最新消息
var NOTICE_INFO_PATH = 'index/notices/get.ajax';

//如何使用
var HOW_TO_USE = 'index/howToUses/get.ajax';

//切换语言
var SWITCH_LAN = 'language.ajax?lang=en';

//成功案例
var SUCCESS_CASE_PATH ='index/successcases/get.ajax';



/**
 * @file js工具函数
 * @author yanlingling@baidu.com
 */
var common = {

	/**
	 *发送请求的函数
	 */
	sendRequest : function(url, data, callback) {
		var me = this;
		var realCallback = function(data){
		    if(data.errorCode == 0) { 
            callback(data.data);
          } else {
            alert('系统异常');
         }
		};
		//common.ajaxCallBack = callback;
		$.ajax({
			type : 'POST',
			url : url,
			data : data,
			success : realCallback,
			contentType : 'application/json',
			dataType : 'json'
		});

		//$.post(url, data, this.allAjaxCallback, "json");
	},

	sendTextRequest : function(url, callback) {
		var me = this;
		return $.ajax({
			url : url,
			async : false
		}).responseText;
	},
	
    navInit:function(index){
        var navs = $("#headBottomContentRight").find('a');
        navs.css('color','#858585');
        var currentNav =navs .eq(index);
        currentNav.css('color','#C53334');
        $("#headBottomContentRight").bgMove({
            css:'heandLinkMoveBg',
            clickClassName:'heandLink',
            main:$("#headBottomContentRight"),
            fixPlaceEle:currentNav
        });
        
    },
    /**
     *语言切换 
     */
     switchLanInit : function(){
         //绑定语言切换
        $("#switchLan").click(function(){
            var path = $(this).attr('link');
             common.sendRequest(path, {}, common.switchLanCallback);

        })
    } ,
      
   
    /**
     *切换语言 回调
     */
    switchLanCallback : function(data){
        if(data == true){
            location.reload() 
        }
       },
 
    /**
     *时间转化
     */ 
   getLocalTime :function (time) {
        var now =  new Date(parseInt(time,10));//.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
          var   year=now.getFullYear();     
          var   month=now.getMonth()+1;     
          var   date=now.getDate();     
        return   year+"-"+month+"-"+date;  
    },
    
    /**
     * 获取url参数
     */
    getURLParam : function getURLParam(key){
    if(typeof key == 'undefined'){
        return '';
    }
    
    var raw = location.search.substr(1).split('&'),
        param = [],
        tmp = [];
    
    for (var i = 0, l = raw.length; i < l; i++){
        tmp = raw[i].split('=');
        param[tmp[0]] = tmp[1];
    }
        
    if(typeof param[key] != 'undefined'){
        return param[key];
    } else {
        return '';
    }
}

 
	/**
	 * 请求先到这里统一处理一下错误
	 * @param {Object} data
	 * @param {Object} textStatus
	 
	allAjaxCallback : function(data) {
	    console.log(data);
		if(data.errorCode == 0) {
			common.ajaxCallBack(data.data);
		} else {
			alert('系统异常');
		}
	}*/
};

/**
 * 获取某个子串在字符串中的位置
 * @param {Object} str
 * @param {Object} substr
 * @author zuming@baidu.com
 */
function getSubstrNumber(str, substr) {
	if (str === "" || substr === "") {
		return 0;
	}
	str = '' + str;
	var _tmp = str.split(substr);
	return _tmp.length - 1;
}


/**
 * 删除字符串中的首尾空白字符
 * @param {String} str 需要处理的字符串
 * @return {String} 处理过的字符串
 * @author dongrui@baidu.com
 */
function trim(str) {
	str = '' + str;
    return str.replace(/(^[\s\u3000\xa0]+|[\s\u3000\xa0]+$)/g, '');
};

/**
 * 编码字符串中的html敏感字符
 * @param {String} str 需要处理的字符串
 * @return {String} 处理过的字符串
 * @author zuming@baidu.com
 */
function escapeHTML(str) {
	str = '' + str;
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
};

/**
 * 反编码字符串中的html敏感字符
 * @param {String} str 需要处理的字符串
 * @return {String} 处理过的字符串
 * @author dongrui@baidu.com
 */
function unescapeHTML(str) {
	str = '' + str;
    return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
};

/**
 * URL Encode编码字符串
 * @param {String} str 需要处理的字符串
 * @return {String} 处理过的字符串
 * @author zuming@baidu.com
 */
function encode(str) {
	str = '' + str;
	return encodeURIComponent(str);
}

/**
 * URL Decode反编码字符串
 * @param {String} str 需要处理的字符串
 * @return {String} 处理过的字符串
 * @author zuming@baidu.com
 */
function decode(str) {
	return decodeURIComponent(str);
}

function escapeQuote(str){
	return str.replace(/'/g, "&#39;").replace(/"/g, '&quot;');
}

function addSlashes(str){
	return str.replace(/'/g,'\\\\\'').replace(/"/g,'\\\\\"');
}

function addSlashesForJson(str){
	return str.replace(/"/g,'\\\\\\\"');
}

/**
 * 字符串求长度(全角)
 * @param {String} str 需要求长的字符串
 * @return {Number} 长度
 * @author zuming@baidu.com
 */
function getLengthCase(str) {
	var len = str.length;
	str.replace(/[\u0080-\ufff0]/g, function (){len++;})
	return len;	
}

/**
 * 字符串截取部分(全角)
 * @param {String} str 字符串
 * @param {Number} len 截断保留长度
 * @return {String} 截断后的字符串
 * @author zuming@baidu.com
 */
function subStrCase(str, len) {
	while (getLengthCase(str) > len) {
		str = str.substr(0, str.length - 1);
	}
	return str;
}

/**
 * 插入软回车
 * @param {Object} s
 * @author zuming@baidu.com
 */
function insertWbr(s) {
	return String(s).replace(/(?:<[^>]+>)|(?:&[0-9a-z]{2,6};)|(.{1})/g, '$&<wbr>').replace(/><wbr>/g, '>');
}

/**
 * 截取字符串
 * @param {Object} str 字符串
 * @param {Object} len 长度
 * @param {Object} tailStr 尾部添加
 * @author zuming@baidu.com
 */
function getCutString(str, len, tailStr) {
	var tmp = unescapeHTML(str);

	if(typeof tailStr == 'undefined'){
		tailStr = '';
	}
	//var len=getLengthCase(tmp)
	if (getLengthCase(tmp) > len) {
		if (tmp == str) {
			tmp = subStrCase(tmp,len-1) + tailStr;	
		} else {
			tmp = escapeHTML(subStrCase(tmp,len-1)) + tailStr;
		}
		return tmp;
	} else {
		return str;
	}
}

/**
 * 每三位增加逗号
 * @param {Object} str
 */
function addCommas(str){
	str += '';
	x = str.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function autoEllipseText(text, width) {
    var el = G("autoEllipseWrapper");
    if (!el) {
        el = document.createElement("div");
        el.id = "autoEllipseWrapper";
        el.style.position = "absolute";
        el.style.left = "-10000px";
        el.style.top = "-10000px";
        document.body.appendChild(el);
    }
    el.innerHTML = "<span id=\"ellipsisSpan\" style=\"white-space:nowrap;\"></span>";

    var inSpan = document.getElementById('ellipsisSpan');
    inSpan.appendChild(document.createTextNode(text));
    if (inSpan.offsetWidth > width) {
        var i = text.length;
        //inSpan.innerHTML = "";
        while (inSpan.offsetWidth > (width)) {
            inSpan.innerHTML = "";
            inSpan.appendChild(document.createTextNode(text.substr(0, i) + "..."));
            i--;
        }
        var returnText = text.substr(0, i + 1) + "...";
        el.innerHTML = "";
        return returnText;
    }
    return text;
}
/**json数据转换？？*/
jsonParse = function (data) {
    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if (!/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
        .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
        return null;
    }
    //优先使用原生的parse
    return window.JSON && window.JSON.parse ?
        window.JSON.parse( data ) :
        (new Function("return " + data))();
};

/*
@author   DengHailong(baidu HI:haiyume)
@date:    2012-6-5
@edition: 1.0.beta
@info:    图片轮播 vpic.js
@relay:   依赖 jquery
*/
(function($){
	$.fn.vpic = function(options){
		var defaults = {
			width:720,
			height:200,
			time:5000,
			bt:true, //是否显示按钮
			color:[] //是否是全屏显示 每张黄灯片的背景颜色值
		};
		var options = $.extend(defaults, options);
		this.each(function(){
			jQuery.easing['jswing'] = jQuery.easing['swing'];
			jQuery.extend(jQuery.easing,{
				easeInExpo: function (x, t, b, c, d) {return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;},
				expoin: function(x, t, b, c, d) {return jQuery.easing.easeInExpo(x, t, b, c, d);}
			});
			var self=$(this),
                eq=0; //当前显示图片索引
                if(self.children().length==0){//html里面没有写图片
                	if(options.imgSource){//圖片也是傳進來的，頁面上沒有創建
				var imgSource = options.imgSource;
				var htmlStr = [];
				for (var i=0; i < imgSource.length; i++) {
				    htmlStr[htmlStr.length] = '<img usemap="#bannerMap'+i+'"  src="'+imgSource[i].imgSrc+'" >';
					if(imgSource[i].clickAreas){ //添加图片映射区
					   htmlStr[htmlStr.length] ='<map name="bannerMap'+i+'"  id="bannerMap'+i+'">';
					
					for(var j=0; j < imgSource[i].clickAreas.length; j++) {
					    var clickParm = imgSource[i].clickAreas[j];
					    var coords=[];
					        coords.push(clickParm.x);
					        coords.push(clickParm.y);
					        coords.push(clickParm.x+clickParm.width);
					        coords.push(clickParm.y+clickParm.width);
					  htmlStr[htmlStr.length] ='<area shape="rect" coords="'+coords.join(',')+'" href ="'+clickParm.href+'" />';
					}
					 htmlStr[htmlStr.length] ='</map>'; 
					}
					
				   
				};  
				self.append(htmlStr.join(''));
			}else{
				alert('缺少image元素哦~')
			}
                }
			
			var size=self.find('img').length;//图片数量
			self.find("img").css({width:options.width,height:options.height});
			
			self.wrapInner('<div class="vpic_box" style="width:'+options.width+'px;"><div class="vpic" style="width:'+size*options.width+'px;"></div></div>');
			
			//全屏幻灯片设置
			if(options.color.length>0){
				if(options.color.length<size){alert('颜色值数量少于图片数量。');return;}
				var sc_width=$(window).width();
				self.children().css({width:sc_width})
					.children().css({width:size*sc_width})
					.find("img").css({padding:'0px '+(sc_width-options.width)/2+'px'})
					.each(function(i){
						$(this).css({backgroundColor:options.color[i]});																					
				});
				if(sc_width<options.width)self.find("img").css({width:sc_width,height:options.height});
				options.width=sc_width; 
			}
			
			
			//初始化按钮
			if(options.bt){
				(function(){
					var bt='';
					for(var i=0; i<size; i++){
						bt+='<a href="javascript:void(0)" ta="'+i+'" title="第'+(i+1)+'页" class="bt_a"></a>';
					}
					self.find(".vpic_box").append('<div class="more_bt_wraper "><div class="more_bt_bgL"></div><div class="more_bt_bgM"></div><div class="more_bt_bgR"></div></div><div class="more_bt">'+bt+'</div>').on("mouseover",".bt_a",function(){
						eq=$(this).attr("ta");																						   
						self.find(".vpic").animate({marginLeft:-eq*options.width},800,"expoin");
						$(this).addClass("bt_a_se").siblings().removeClass("bt_a_se");
					}).find(".bt_a").eq(0).addClass("bt_a_se");
					self.find(".more_bt").css({marginLeft:-22*size/2,width:22*size+10});
					self.find(".more_bt_bgM").css({width:22*size-15});
                
				})();
			}
			
			//执行循环
			var c_sub=function(){
				eq++;
				if(eq>=size){eq=0;}
				self.find(".vpic").animate({marginLeft:-eq*options.width},800,"expoin");
				if(self.find(".bt_a").length>0){self.find(".bt_a").eq(eq).addClass("bt_a_se").siblings().removeClass("bt_a_se");}
			};
			var sub_t=window.setInterval(function(){c_sub();},options.time);
			
			self.hover(function(){
				window.clearInterval(sub_t);
				sub_t=null;
			},function(){
				sub_t=window.setInterval(function(){c_sub();},options.time);
			});
			
			
		});
	};
})(jQuery);

/*
 @author   yanlingling
 @date:    2012-12-19
 @edition:
 @info:    ����ƶ���ʱ�� �������Ŷ�
 @relay:   ���� jquery
 */
(function($) {
    $.fn.bgMove = function(options) {
        var defaults = {
            css : '',
            clickClassName : ''

        };
        var options = $.extend(defaults, options);
        this.each(function() {
            var self = $(this);
            self.append('<div class="' + options.css + '"></div>');
            var elements = self.find("." + options.clickClassName);

            elements.mouseover(function() {
                var x = $(this).position().left;
                var width = $(this).css('width');
                var bg = self.find("." + options.css);
                bg.show();
                bg.css({
                    'width' : width
                });
                bg.animate({
                    left : x
                }, 500);
               
            });
            if(options.fixPlaceEle && options.fixPlaceEle.length != 0) {//鼠标离开需要复位
                var bg = self.find("." + options.css);
                var rawx = options.fixPlaceEle.position().left;
                var rawwidth = options.fixPlaceEle.css('width');
                var bg = self.find("." + options.css);
                bg.css({
                    'width' : rawwidth
                });
                bg.css({
                    "left" : rawx
                });

                options.main.mouseleave(function() {
                    //var x = options.fixPlaceEle.position().left-20;
                    //var width=options.fixPlaceEle.css('width');

                    bg.css({
                        'width' : rawwidth
                    });
                    bg.animate({
                        left : rawx
                    }, 250);
                })
            } else {
                var bg = self.find("." + options.css);
                bg.hide();
                options.main.mouseleave(function() {
                    bg.hide();
                })
            }

        });
    };
})(jQuery);

